package com.coldwindblows.blog.controller.admin;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.coldwindblows.blog.bo.RestResponseBo;
import com.coldwindblows.blog.controller.BaseController;
import com.coldwindblows.blog.pojo.CommentDo;
import com.coldwindblows.blog.pojo.UserDo;
import com.coldwindblows.blog.service.ICommentService;
import com.github.pagehelper.PageInfo;

/**
 * Created by ColdWindBlows on 2018/07/06
 *
 */
@Controller
@RequestMapping("/admin/comments")
@SuppressWarnings("rawtypes")
public class CommentController extends BaseController {
	
	@Autowired
	private ICommentService commentService;
	
	@GetMapping("")
	public String index(@RequestParam(value = "page", defaultValue = "1") int page, @RequestParam(value = "limit", defaultValue = "15") int limit, HttpServletRequest request) {
		UserDo user = this.user(request);
		CommentDo temp = new CommentDo();
		//temp.setAuthorId(user.getUid());
		temp.setOwnerId(user.getUid());
		PageInfo<CommentDo> pageList = commentService.getCommentsWithPage(temp, page, limit);
		request.setAttribute("comments", pageList);
		return "admin/comment_list";
	}
	
	/**
	 * 删除一条评论
	 * @param coid
	 * @return
	 */
	@PostMapping("/delete")
	@ResponseBody
	public RestResponseBo delete(@RequestParam Integer coid) {
		try {
			CommentDo comment = commentService.getDetail(coid);
			if(null == comment) {
				return RestResponseBo.fail("不存在的评论");
			}
			commentService.deleteComment(coid, comment.getCid());
		} catch(Exception e) {
			String msg = "评论删除失败";
			return RestResponseBo.fail(msg);
		}
		return RestResponseBo.ok();
	}
	
	@PostMapping("/status")
	@ResponseBody
	public RestResponseBo delete(@RequestParam Integer coid, @RequestParam String status) {
		try{
			CommentDo comment = commentService.getDetail(coid);
			if(comment == null) {
				return RestResponseBo.fail("操作失败");
			}
			comment.setCoid(coid);
			comment.setStatus(status);
			commentService.updateComment(comment);
		} catch(Exception e) {
			String msg = "操作失败";
			return RestResponseBo.fail(msg);
		}
		
		return RestResponseBo.ok();
	}
}
